/**
 * Created by Administrator on 2015/3/16.
 */

(function(){
	//table小插件
	var $Table = function($table,config){
		config = config || {};
		var odd = config.odd || "#fff";//奇
		var even = config.even || "#fcfcfc";//偶
		var hover = config.hover || "#f7f7f7";//mouse hover
		var onClick = config.onClick;
		$table.find("tbody>tr").each(function(index){
			var $tr = $(this);
			if(index%2==0){
				$tr.addClass("even").css("backgroundColor",even);
			}else{
				$tr.addClass("odd").css("backgroundColor",odd);
			}
		})
		$table.on("mouseover","tbody>tr",function(e){
			$(e.currentTarget).css("backgroundColor",hover)
		})
		$table.on("mouseout","tbody>tr",function(e){
			var $tr = $(e.currentTarget);
			if($tr.hasClass("odd")){
				$tr.css("backgroundColor",odd);
			}else{
				$tr.css("backgroundColor",even);
			}
		})
		$table.on("click",function(e){
			onClick(e);
		})
	};
	$Table.refresh = function($table){
		var even = $table.find(".even").first().css("backgroundColor");
		var odd = $table.find(".odd").first().css("backgroundColor");
		$table.find("tbody>tr").each(function(index){
			var $tr = $(this);
			if(index%2==0){
				even && $tr.removeClass("odd").addClass("even").css("backgroundColor",even);
			}else{
				odd && $tr.removeClass("even").addClass("odd").css("backgroundColor",odd);
			}
		})
	}
	var AJAX_URL = "http://www.12301.cc/call/jh_alliance.php";
	var getUid = function(){
		return $("#alliance_uid").val();
	};
	var getData = function(values){
		if(!values) return false;
		var result = [];
		values = values.split("|");
		for(var i in values){
			var d = values[i].split("&");
			var json = {};
			json["value"] = d[0];
			json["id"] = d[1];
			json["dai"] = d[2];
			result.push(json);
		}
		return result;
	};
	var getProData = (function(){
		var result = null;
		return function(){
			return result ? result : result = getData($("#proSelectHid").val());
		}
	})();
	var getDaiData = (function(){
		var result = null;
		return function(){
			return result ? result : result = getData($("#dailiSelectHid").val());
		}
	})();
	var buildHtml = function(data,cls,filter){
		var html = "";
		for(var i in data){
			var d = data[i];
			var id = d["id"];
			var text = d["value"];
			var dai = d["dai"];
			if(typeof filter=="function" && filter(id)) continue;
			if(dai){
				html += '<li class="item '+cls+'" data-id="'+id+'" data-dai="'+dai+'">'+text+'</li>';
			}else{
				html += '<li class="item '+cls+'" data-id="'+id+'">'+text+'</li>';
			}
		}
		return html;
	};
	var buildCityHtml = function(data){
		var html = "";
		for(var i in data){
			var d = data[i];
			var cityId = d["n_code"];
			var value = d["city"];
			var dai = d["agent"];
			html += '<li class="item cityItem" data-dai="'+dai+'" data-id="'+cityId+'">'+value+'</li>';
		}
		return html;
	};
	function initTab(){
		$("#tabHead").on("click","li",function(e){
			var target = $(e.currentTarget);
			var index = target.index();
			$("#tabHead>li").removeClass("active");
			target.addClass("active");
			$("#allianceMod>.tabPannel").hide().eq(index).show();
		})
	}
	//利润分配
	function Pmatch(){
		this.container = $("#profitPannel");
		this.saveBtn = this.container.children(".saveBtn");
		this.init();
	}
	Pmatch.prototype = {
		init : function(){
			var that = this;
			var container = this.container;
			this.alliNameInitVal =  $("#alliNameInp").val();
			container.on("focus",".textInp",function(e){
				var tarInp = $(e.target);
				tarInp.data("lastVal",tarInp.val());
			})
			container.on("blur",".textInp",function(e){
				var tarInp = $(e.target);
				that.onBlur(tarInp);
			})
			container.on("click",".saveBtn",function(e){
				var btn = $(e.currentTarget);
				if(btn.hasClass("disabled")) return false;
				var alliNameInp = $("#alliNameInp");
				var alliNameVal = alliNameInp.val();
				if(!alliNameVal){
					alert("请输入联盟名称");
					return false;
				}
				that.submit();
				return false;
			})
			$("#profitPannel .profitUl").children().each(function(){
				var itemUl = $(this);
				that.groupInpsPlus(itemUl)
			})
		},
		//验证输入的值   必须为正整数 不能为空  可以为0 100
		onBlur : function(tarInp){
			var siblingInps;
			var siblingTotalVal = 0;
			var curVal = tarInp.val();
			//上一次修改的植
			var lastVal = tarInp.data("lastVal");
			var tip = tarInp.parents(".profitLine").children(".tip");
			if(tarInp.hasClass("alliNameInp")){
				if(!curVal) tarInp.val(lastVal);
				return;
			}
			if(curVal==""){
				tarInp.val(lastVal);
				return;
			}
			if(curVal>100){
				alert("利润分配最大不能超过100");
				tarInp.val(lastVal);
				return;
			}
			if(!PFT_GLOBAL.U.isPositiveNum(curVal) && curVal!="0"){
				alert("请输入正整数");
				tarInp.val(lastVal);
				return;
			}
			this.groupInpsPlus(tarInp.parents(".itemUl"));
		},
		//鼠标blur时计算此input所在组内所有input的总和
		groupInpsPlus : function(group){
			if(!group) return false;
			var inps = group.find(".textInp");
			var total = group.find(".groupTotalVal");
			var val = 0;
			inps.each(function(){
				val += Number($(this).val());
			})
			total.text(val);
			this.allGroupInpsPlus();
		},
		allGroupInpsPlus : function(){
			var val = 0;
			var container = $("#allGroupTotalVal");
			var total = container.children(".num");
			$("#profitPannel .groupTotalVal").each(function(){
				val += Number($(this).text())
			})
			total.text(val);
			if(val!=100){
				container.addClass("error");
				this.saveBtn.addClass("disabled").text("利润比例总和必为100%");
			}else{
				container.removeClass("error");
				this.saveBtn.removeClass("disabled").text("保存");
			}
		},
		//提交保存 异步
		submit : function(){
			var data = {};
			var container = this.container;
			var saveBtn = this.saveBtn;
			var uid = getUid();
			if(!uid){
				console && console.log("缺省uid");
				return false;
			}
			data["alliName"] = $("#alliNameInp").val();
			data["profit_a"] = container.find("input[name=profit_a]").val();
			data["profit_b"] = container.find("input[name=profit_b]").val();
			data["profit_c"] = container.find("input[name=profit_c]").val();
			data["profit_d"] = container.find("input[name=profit_d]").val();
			data["profit_e"] = container.find("input[name=profit_e]").val();
			data["profit_f"] = container.find("input[name=profit_f]").val();
			data["profit_g"] = container.find("input[name=profit_g]").val();
			//data["profit_x"] = container.find("input[name=profit_x]").val();
			//data["profit_y"] = container.find("input[name=profit_y]").val();
			data["action"] = "modify";
			data["uid"] = uid;
			data["protocol"] = $("#xieyiTextarea").val();
			console.log(data)
			PFT_GLOBAL.G.Ajax({
				url : AJAX_URL,
				type : "POST",
				dataType : "JSON",
				data : data,
				loading : function(){ saveBtn.text("正在保存...")},
				removeLoading : function(){ saveBtn.text("保存")},
				timeout : function(){ alert("保存超时")},
				serverError : function(){ alert("jh_alliance接口出错")}
			},function(res){
				if(res.status == "success"){
					PFT_GLOBAL.U.Alert("success",'<p style="width:200px">保存成功</p>')
				}else{
					alert(res.mesg);
				}
			})
		}
	};

	/**
	 * 弹出框保存提交
	 * @param code  省或市的id(code)
	 * @param agentId 代理商id
	 * @returns {boolean}
	 */
	var submit = function(code,agentId,container,action,config){
		if(!code || !agentId){
			console && console.log("缺省code或agentId");
			return false;
		}
		action = action || "操作";
		PFT_GLOBAL.G.Ajax({
			url : AJAX_URL,
			type : "POST",
			dataType : "json",
			data : {
				action : "agent_set",
				ac : code,
				agent : agentId
			},
			loading : function(){ container.children(".loadingMask").show()},
			removeLoading : function(){ container.children(".loadingMask").hide()},
			timeout : function(){ console && console.log("请求call/jh_alliance.php接口超时 action:agent_set&ac="+code+"&agent="+agentId)},
			serverError : function(){ console && console.log("请求call/jh_alliance.php接口出错 action:agent_set&ac="+code+"&agent="+agentId)}
		},function(res){
			if(res.status && res.status=="success"){
				PFT_GLOBAL.U.Alert("success",'<p style="width:200px">'+action+'成功</p>');
				if(!config) return false;
				var $table = config.$table;
				var pro = config.pro;
				var proId = config.proId;
				var city = config.city;
				var cityId = config.cityId;
				var dai = config.dai;
				var daiId = config.daiId;
				var rid = res.rid;
				var date = res.date;
				var code = proId ? proId : cityId;
				var tit = pro ? pro : city;
				var poper = config.poper;
				var update = false;
				var html = "";
				$table.find("tbody>tr").each(function(tr,index){
					var tr = $(this);
					var _code = tr.attr("data-code");
					if(_code==code && _code!=""){
						update = true;
						tr.attr("data-dai",daiId).data("dai",daiId).children(".dai").text(dai);
						return false;
					}
				})
				if(!update){
					html += '<tr data-code="'+code+'" data-dai="'+daiId+'" data-rid="'+rid+'">';
					html += '<td class="procity cleft">'+tit+'</td>';
					html += '<td class="cleft dai">'+dai+'</td>';
					html += '<td>'+date+'</td>';
					html += '<td class="removeTd"><a class="editBtn" href="#">更换</a><a class="removeBtn" href="#">删除</a></td>';
					html += '</tr>';
					$table.append(html);
					$Table.refresh($table);
				}
				poper && poper.close && poper.close();
			}else if(res.status && res.status=="fail"){
				var mesg = res.mesg ? res.mesg : action+"失败，请稍后重试";
				PFT_GLOBAL.U.Alert("fail",'<p style="width:200px">'+mesg+'</p>');
			}else{
				console && console.log("请求call/jh_alliance.php接口出错 action:agent_set&ac="+code+"&agent="+agentId);
			}
		})
	};
	//删除代理商
	var removeDai = function(removeBtn){
		var tr = removeBtn.parents("tr");
		var $table = tr.parents("table");
		var daiId = tr.data("dai");
		var rid = tr.data("rid");
		if(!rid){
			console && console.log("缺省rid");
			return false;
		}
		PFT_GLOBAL.G.Ajax({
			url : AJAX_URL,
			type : "POST",
			dataType : "JSON",
			data : {
				action : "agent_clear",
				rid : rid,
				id : daiId
			},
			loading : function(){
				removeBtn.text("删除中...")
			},
			removeLoading : function(){
				removeBtn.text("删除")
			},
			timeout : function(){
				alert("请求超时，请稍后重试")
			},
			serverError : function(){
				console && console.log("请求call/jh_alliance.php接口出错 action:agent_clear&id="+daiId);
			}
		},function(res){
			if(res.code == "success"){
				PFT_GLOBAL.U.Alert("success",'<p style="width:200px">删除成功</p>');
				tr.remove();
				$Table.refresh($table);
			}else{
				res.mesg &&  PFT_GLOBAL.U.Alert("fail",'<p stype="width:200px">'+res.mesg+'</p>');
			}
		})
	};
	//打开更换代理商弹窗
	var openUpdateDai = function(removeBtn){
		var container = $("#updateDialogContainer");
		var dialog = container.data("dialog");
		var input = $("#updSelectInp");
		var tr = removeBtn.parents("tr");
		var procity = tr.children(".procity").text();
		var code = tr.data("code");
		var daiId = tr.children(".dai").attr("data-id");
		var dai = tr.children(".dai").text();
		var listUl = $("#upSelectInp_listUl_add");
		//更换代理商
		var updateDai = function(code,dai,daiTxt){
			console.log("code="+code+" dai="+dai+" daiTxt="+daiTxt)
			if(!code || !dai) return false;
			PFT_GLOBAL.G.Ajax({
				url : AJAX_URL,
				type : "POST",
				dataType : "json",
				data : {
					action : "agent_set",
					ac : code,
					agent : dai
				},
				loading : function(){ removeBtn.text("更换中...")},
				removeLoading : function(){ removeBtn.text("更换")},
				timeout : function(){ console && console.log("请求call/jh_alliance.php接口超时 action:agent_set&ac="+code+"&agent="+agentId)},
				serverError : function(){ console && console.log("请求call/jh_alliance.php接口出错 action:agent_set&ac="+code+"&agent="+agentId)}
			},function(res){
				if(res.status && res.status=="success"){
					PFT_GLOBAL.U.Alert("success",'<p style="width:200px">更换成功</p>');
					tr.children(".dai").text(daiTxt);
				}else if(res.status && res.status=="fail"){
					var mesg = res.mesg ? res.mesg : "更换失败，请稍后重试";
					PFT_GLOBAL.U.Alert("fail",'<p style="width:200px">'+mesg+'</p>');
				}else{
					console && console.log("请求call/jh_alliance.php接口出错 action:agent_set&ac="+code+"&agent="+agentId);
				}
			})
		};
		container.find(".tit").html('为<span style="margin:0 4px; font-size:16px;">'+procity+'</span>更换代理商');
		if(!code){
			console && console.log("缺省code");
			return false;
		}
		if(!dialog){
			dialog = new PFT_GLOBAL.U.Dialog({
				maskId : "#gMask",
				containerId : "#updateDialogContainer",
				maskBg : "#000",
				maskOpacity : 0.5
			})
			var data = getDaiData();
			var html = buildHtml(data,"daiItem");
			listUl.html(html);
			dialog.on("click",function(e){
				var target = $(e.target);
				if(target.hasClass("daiItem")){
					target.addClass("active").siblings().removeClass("active");
					listUl.prev().val(target.text()).data("id",target.data("id"));
				}else if(target.attr("id")=="updateDaiSubmit"){
					var daiTxt = input.val();
					var daiId = input.data("id");
					console.log(target)
					dialog.close();
					updateDai(code,daiId,daiTxt);
				}
			})
			container.data("dialog",dialog);
		}
		listUl.children().each(function(){
			var item = $(this);
			var daiTxt = item.text();
			if(daiTxt==dai){
				item.trigger("click");
				return false;
			}
		})
		dialog.open();
	};
	//添加省市代理 -- 新
	(function(){
		var Dialog = PFT_GLOBAL.U.Dialog;
		var pDialog = null;
		var cDialog = null;
		var proIdFilter = {
			"1000" : 1000,
			"1100" : 1100,
			"2900" : 2900,
			"6530" : 6530,
			"5998" : 5998,
			"5999" : 5999,
			"5997" : 5997
		};
		//根据省级id查询其对应的市级
		var queryCityById = function(id){
			if(!id) return false;
			var listUl = $("#cSelectInp_listUl_add");
			var data = listUl.data("city"+id);
			if(data){
				listUl.html(buildCityHtml(data));
				return false;
			}
			PFT_GLOBAL.G.Ajax({
				url : AJAX_URL,
				type : "GET",
				dataType : "JSON",
				data : {
					action : "agents",
					ac : id
				},
				loading : function(){
					listUl.html('<li class="nocity" style="height:100%; line-height:200px; width:100%; padding:0; margin:0; border-bottom:0 none; text-align:center">正在加载...</li>')
				},
				removeLoading : function(){ listUl.html("")},
				timeout : function(){ console && console.log("请求call/jh_alliance.php接口超时 action:agents&ac="+id)},
				serverError : function(){ console && console.log("请求call/jh_alliance.php接口出错 action:agents&ac="+id)}
			},function(res){
				if(Object.prototype.toString.call(res) == "[object Array]" && res.length==0){ //空数据
					listUl.html('<li class="nocity" style="height:100%; line-height:200px; width:100%; padding:0; margin:0; border-bottom:0 none; text-align:center">请直接加省代理</li>');
				}else{
					listUl.data("city"+id,res);
					listUl.html(buildCityHtml(res));
					$("#cSelectInp_listUl_add").children(":first").trigger("click");
				}
			})
		};
		//省
		var initDialog = function(){
			var proListUl = $("#pSelectInp_listUl_add");
			var daiListUl = $("#dSelectInp_listUl_add");
			var pdata = getProData();
			var phtml = buildHtml(pdata,"proItem",function(id){
				return proIdFilter[id] ? true : false;
			});
			var ddata = getDaiData();
			var dhtml = buildHtml(ddata,"daiItem");
			proListUl.html(phtml);
			daiListUl.html(dhtml);
			pDialog = new Dialog({
				maskId : "#gMask",
				containerId : "#proDialogContainer",
				maskBg : "#000",
				maskOpacity : 0.5
			});
			pDialog.on("click",function(e){
				var target = $(e.target);
				var id = target.data("id");
				var value = target.text();
				var daiId = target.data("dai");
				var container = $("#proDialogContainer");
				if(target.hasClass("item")){
					target.addClass("active").siblings().removeClass("active");
					target.parent().prev().val(value).data("id",id);
					if(daiId && daiId!="0"){
						daiListUl.children().each(function(){
							var $this = $(this);
							var id = $this.data("id");
							var txt = $this.text();
							if(id == daiId){
								$("#dSelectInp").val(txt).data("id",id);
								return false;
							}
						})
					}
				}else if(target.attr("id")=="addProSubmit"){
					var proInp = $("#pSelectInp");
					var daiInp = $("#dSelectInp");
					var code = proInp.data("id");
					var pro = proInp.val();
					var dai = daiInp.val();
					var agentId = daiInp.data("id");
					if(!code || !agentId){
						console && console.log("缺省省id或代理商id");
						alert("请先选择一个省份，再在右边为此省选定一个代理商");
						return false;
					}
					submit(code,agentId,container,"添加",{
						$table : $("#prodaiTable"),
						proId :code,
						pro : pro,
						dai : dai,
						daiId : agentId,
						poper : pDialog
					});
				}
			})
		};
		//市
		var initCityDialog = function(){
			var proListUl = $("#pcSelectInp_listUl_add");
			var daiListUl = $("#dcSelectInp_listUl_add");
			var cityListUl = $("#cSelectInp_listUl_add");
			var pdata = getProData();
			var phtml = buildHtml(pdata,"proItem",function(id){
				return proIdFilter[id] ? true : false;
			});
			var ddata = getDaiData();
			var dhtml = buildHtml(ddata,"daiItem");
			proListUl.html(phtml);
			daiListUl.html(dhtml);
			cDialog = new Dialog({
				maskId : "#gMask",
				containerId : "#cityDialogContainer",
				maskBg : "#000",
				maskOpacity : 0.5
			});
			cDialog.on("click",function(e){
				var target = $(e.target);
				var id = target.data("id");
				var value = target.text();
				var daiId = target.data("dai");
				var container = $("#cityDialogContainer");
				if(target.hasClass("item")){
					target.addClass("active").siblings().removeClass("active");
					target.parent().prev().val(value).data("id",id);
					if(target.hasClass("proItem")){
						queryCityById(id);
					}
					if(target.hasClass("city") && daiId && daiId!="0"){
						daiListUl.children().each(function(){
							var $this = $(this);
							var id = $this.data("id");
							var txt = $this.text();
							if(id == daiId){
								$("#dSelectInp").val(txt).data("id",id);
								return false;
							}
						})
					}
				}else if(target.attr("id")=="addCitySubmit"){
					var proInp = $("#pcSelectInp");
					var cityInp = $("#cSelectInp");
					var daiInp = $("#dcSelectInp");
					var cityId = cityInp.data("id");
					var agentId = daiInp.data("id");
					var pro = proInp.val();
					var dai = daiInp.val();
					var city = cityInp.val();
					city = pro ? (pro+city) : city;
					if(!cityId || !agentId){
						console && console.log("缺省市id或代理商id");
						alert("请先选择市，再在右边为此省选定一个代理商");
						return false;
					}
					submit(cityId,agentId,container,"添加",{
						$table : $("#citydaiTable"),
						cityId : cityId,
						dai : dai,
						daiId : agentId,
						city : city,
						poper : cDialog
					});
				}
			})
		};
		$("#addProdaiBtn").on("click",function(){
			var btn = $(this);
			var init = btn.data("init");
			if(init!=="true"){
				btn.data("init","true");
				initDialog();
			}
			pDialog.open();
			return false;
		})
		$("#addCitydaiBtn").on("click",function(){
			var btn = $(this);
			var init = btn.data("init");
			if(init!=="true"){
				btn.data("init","true");
				initCityDialog();
			}
			cDialog.open();
			return false;
		})
	})();




	$(function(){
		initTab();
		new Pmatch();
		$Table($("#prodaiTable"),{
			odd : "#fff",
			even : "#fcfcfc",
			hover : "#f7f7f7",
			onClick : function(e){
				var target = $(e.target);
				target.hasClass("removeBtn") && removeDai(target);
				target.hasClass("editBtn") && openUpdateDai(target);
			}
		})
		$Table($("#citydaiTable"),{
			odd : "#fff",
			even : "#fcfcfc",
			hover : "#f7f7f7",
			onClick : function(e){
				var target = $(e.target);
				target.hasClass("removeBtn") && removeDai(target);
				target.hasClass("editBtn") && openUpdateDai(target);
			}
		})
	})

})();
